package com.xnfh.equipment.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.lxj.xpopup.XPopup
import com.xnfh.common.bean.EquipmentToken
import com.xnfh.common.bean.EquipmentTokenV1
import com.xnfh.common.bean.FindFieldRecordSRecord
import com.xnfh.common.bean.GatDeviceValvesListBean
import com.xnfh.common.bean.GateWayTotalInfoBean
import com.xnfh.common.manager.UserInfoManager
import com.xnfh.equipment.R
import com.xnfh.equipment.adapter.SensorInfoAdapter
import com.xnfh.equipment.adapter.SensorValuesAdapter
import com.xnfh.equipment.databinding.ActivityKcEquipmentDetailBinding
import com.xnfh.equipment.viewmodel.KcEquipmentDetailViewModel
import com.xnfh.framework.base.BaseActivity
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.network.constant.SFJ_API_TOKEN
import com.xnfh.network.constant.SFJ_NAME_V1
import com.xnfh.network.constant.SFJ_TOKEN_V1
import com.xnfh.network.constant.SFJ_TOKEN_V2

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/12/25 14:21
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/12/25 14:21
 * @UpdateRemark: 更新说明
 */
class KcEquipmentDetailActivity : BaseActivity<ActivityKcEquipmentDetailBinding>(),View.OnClickListener {
    override fun getLayoutID(): Int = R.layout.activity_kc_equipment_detail

    companion object {
        fun start(context: Context, bundle: Bundle? = null) {
            val intent = Intent(context, KcEquipmentDetailActivity::class.java)
            bundle?.let {
                intent.putExtra("bundle", bundle)
            }
            context.startActivity(intent)
        }
    }

    private var viewModel: KcEquipmentDetailViewModel? = null
    //横向的adapter
    private var hAdapter : SensorInfoAdapter? = null
    //下方阀门开关
    private var famenAdapter: SensorValuesAdapter? = null
    //点击的那个阀门
    private var gatDeviceValvesListBean: GatDeviceValvesListBean? = null
    //点击的阀门下标
    private var adapterPosition = -1

    //200表示新KC设备阀门开关调用v2，13调用v1
    private var gatewayType: Int = 200

    //是否是刷新列表
    private var isRefresh: Boolean = true
    private var gateWayId: String? = null


    override fun init(savedInstanceState: Bundle?) {
        setHeaderTitle(getString(R.string.equipment_details))
        mBind.equipmentLookLog.setOnClickListener(this)
        val bundleExtra = intent.getBundleExtra("bundle")
        gateWayId = bundleExtra?.getString("id")
        mBind.equipmentDetailHRecycle.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        hAdapter = SensorInfoAdapter()
        mBind.equipmentDetailHRecycle.adapter = hAdapter
        mBind.equipmentDetailRecycle.layoutManager =
            StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        famenAdapter = SensorValuesAdapter()
        mBind.equipmentDetailRecycle.adapter = famenAdapter
        mBind.equipmentDetailRefresh.setEnableLoadMore(false)
        mBind.equipmentDetailRefresh.autoRefresh()
        showLoadingDialog()//这个加载的loading放在这里是因为进来就要展示，如果放到autoRefresh（）中的话，就会有延迟
        mBind.equipmentDetailRefresh.setOnRefreshListener {
            isRefresh = true
            requestToken()
        }
        famenAdapter?.addChildClickViewIds(R.id.item_sensor_info_check)
        famenAdapter?.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.item_sensor_info_check ->{
                    val roleGroupIds = UserInfoManager.instance.getUserInfo()?.roleGroupIds
                    if(roleGroupIds == null){
                        TipsToast.showTips(R.string.error_tips)
                        return@setOnItemChildClickListener
                    }
                    if(roleGroupIds == "3" || roleGroupIds == "4"){
                        adapterPosition = position
                        gatDeviceValvesListBean = adapter.data[position] as GatDeviceValvesListBean
                        XPopup.Builder(this).asConfirm(getString(com.xnfh.framework.R.string.str_tips),getString(R.string.open_checkbox)){
                            requestToken()
                        }.show()
                    }else{
                        TipsToast.showTips(R.string.error_tips)
                    }
                }
            }
        }

    }

    override fun observe() {
        viewModel = KcEquipmentDetailViewModel()
        viewModel?.tokenV2?.observe(this, object : BaseStateObserver<EquipmentToken>() {
            override fun getRespDataSuccess(it: EquipmentToken) {
                super.getRespDataSuccess(it)
                SFJ_API_TOKEN = it.apiToken
                SFJ_TOKEN_V2 = it.TokenV2
                //如果是列表刷新的，就要请求对应的接口
                if (isRefresh) {
                    viewModel?.requestKcDetail(gateWayId)
                }else{
                    val switchstatus = famenAdapter?.data?.get(adapterPosition)?.Switchstatus
                    val newStatus = if(switchstatus == 1){
                        0
                    }else{
                        1
                    }
                    viewModel?.openCloseFm(gatewayType,gateWayId,gatDeviceValvesListBean?.Deviceid,newStatus,gatDeviceValvesListBean?.DeviceIndex,
                        gatDeviceValvesListBean?.ConfigData)
                }
            }

            override fun getRespDataError() {
                super.getRespDataError()
                dismissLoadingDialog()
            }
        })
        viewModel?.tokenV1?.observe(this,object :BaseStateObserver<EquipmentTokenV1>(){
            override fun getRespDataSuccess(it: EquipmentTokenV1) {
                super.getRespDataSuccess(it)
                SFJ_TOKEN_V1 = it.authorizationEncodeToken
                SFJ_NAME_V1 = it.username
                val switchstatus = famenAdapter?.data?.get(adapterPosition)?.Switchstatus
                val newStatus = if(switchstatus == 1){
                    0
                }else{
                    1
                }
                viewModel?.openCloseFm(gatewayType,gateWayId,gatDeviceValvesListBean?.Deviceid,newStatus,gatDeviceValvesListBean?.DeviceIndex,
                    gatDeviceValvesListBean?.ConfigData)
            }
        })
        viewModel?.KcDetailBean?.observe(this, object : BaseStateObserver<GateWayTotalInfoBean>() {
            override fun getRespDataError() {
                super.getRespDataError()
                dismissLoadingDialog()
            }
            override fun getRespDataSuccess(it: GateWayTotalInfoBean) {
                super.getRespDataSuccess(it)
                dismissLoadingDialog()
                isRefresh = false
                mBind.equipmentDetailRefresh.finishRefresh()
                mBind.equipmentDetailName.text = it.GatGatewayBasicInfo.Gatewayname
                mBind.equipmentDetailStatus.text = if (it.GatGatewayBasicInfo.Waterstatus == 1) {
                    getString(R.string.equipment_irrigate)
                } else {
                    getString(R.string.equipment_no_irrigate)
                }
                hAdapter?.setNewInstance(it.GatDeviceSensorList.toMutableList())
                val gatDeviceValvesList = it.GatDeviceValvesList.toMutableList()
                //如果大于3条的话，就需要把前两条放到最后两条
                if(gatDeviceValvesList.size > 3){
                    val gatDeviceValvesListBean = gatDeviceValvesList[0]//获取第一条
                    val gatDeviceValvesListBean1 = gatDeviceValvesList[1]//获取第二条
                    gatDeviceValvesList.removeFirst()//删除第一条
                    gatDeviceValvesList.removeFirst()//删除第二条
                    gatDeviceValvesList.add(gatDeviceValvesListBean)//添加第一条
                    gatDeviceValvesList.add(gatDeviceValvesListBean1)//添加第二条
                }
                famenAdapter?.setNewInstance(gatDeviceValvesList)
            }
        })

        viewModel?.KcCloseOpenFm?.observe(this,object : BaseStateObserver<Any>(){
            override fun getRespSuccess() {
                super.getRespSuccess()
                TipsToast.showTips(R.string.check_success)
                if(adapterPosition != -1){
                    val switchstatus = famenAdapter?.data?.get(adapterPosition)?.Switchstatus
                    val newStatus = if(switchstatus == 1){
                         0
                    }else{
                        1
                    }
                    famenAdapter?.data?.get(adapterPosition)?.Switchstatus = newStatus
                    famenAdapter?.notifyItemChanged(adapterPosition)
                }
            }
        })

    }


    private fun requestToken() {
        if (gatewayType == 200) {
            viewModel?.requestKcTokenV2()
        } else {
            viewModel?.requestKcTokenV1()
        }
    }

    override fun onClick(v: View?) {
        when(v){
            mBind.equipmentLookLog ->{
                val bundle = Bundle()
                bundle.putString("id",gateWayId)
                KcEquipmentLogActivity.start(this,bundle)
            }
        }
    }

}